#include <REGX52.H>

//对端口重新定义,模块化命名规则DS1302_
sbit DS1302_SCLK = P3^6;
sbit DS1302_IO = P3^4;   //位变量，只进行逻辑判断，非零即真
sbit DS1302_CE = P3^5;

#define DS1302_SECOND   0x80
#define DS1302_MINTUE   0x82
#define DS1302_HOUR     0x84
#define DS1302_DATE     0x86
#define DS1302_MONTH    0x88
#define DS1302_DAY      0x8A
#define DS1302_YEAR     0x8C
#define DS1302_WP       0x8E //写保护的

unsigned char DS1302_Time[9]={22,5,25,23,59,55,3};//年月日时分秒星期

void DS1302_Init(void)
	{   //上电默认1，先初始化为0
	DS1302_CE    = 0;
	DS1302_SCLK  = 0;
}

//---   写一个字节，写到寄存器里，模拟时序
void DS1302_WriteByte(unsigned char Command,Data)
{
	unsigned char i;
	DS1302_CE = 1;
	
	for(i=0;i<8;i++){
		DS1302_IO = Command&(0x01<<i);
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
	}
	
//上边for循环的第0位分析	//写入第0位
//	DS1302_IO = Command&0x01;   //取八位数据command的第零位，就&0x01
//	//&运算 同时为1，才为1，&0的时候就是0，&1就取出当前那位置的数据
//	DS1302_SCLK = 1;   //置1立马 置0，时钟芯片可以承受
//	DS1302_SCLK = 0;
	
	
	for(i=0;i<8;i++){
		DS1302_IO = Data&(0x01<<i);
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
	}
	DS1302_CE = 0;	
}


//---   单字节读取
unsigned char DS1302_ReadByte(unsigned char Command)
{
	unsigned char i,Data = 0x00;//函数局部变量未初始化，值不一定为0
	Command |= 0x01;  //最低位是1，读的状态
	DS1302_CE = 1;
	for(i=0;i<8;i++){
		DS1302_IO = Command&(0x01<<i);
		DS1302_SCLK = 0;
		DS1302_SCLK = 1;//调换一下顺序，因为这个时序，少一个脉冲，防止数据丢失	
	}
	

	
	for(i=0;i<8;i++){
		//再调换回来，连续两次置1，电平无变化，对应那个时序，去掉一个脉冲
		DS1302_SCLK = 1;//给第零位 
		DS1302_SCLK = 0;
		if(DS1302_IO){Data |= (0x01<<i);}//或运算用来置1
	}
	DS1302_CE = 0;
	DS1302_IO = 0;
	return Data;
}

void DS1302_SetTime(void) //此函数把数组DS1302_Time数据（年月日...） 写到时钟芯片里，
{
	DS1302_WriteByte(DS1302_WP,0x00);//此句WP给0，解除芯片写保护
	DS1302_WriteByte(DS1302_YEAR, DS1302_Time[0]/10*16+DS1302_Time[0]%10);//十进制转BCD码
	DS1302_WriteByte(DS1302_MONTH, DS1302_Time[1]/10*16+DS1302_Time[1]%10);	
	DS1302_WriteByte(DS1302_DATE, DS1302_Time[2]/10*16+DS1302_Time[2]%10);
	DS1302_WriteByte(DS1302_HOUR, DS1302_Time[3]/10*16+DS1302_Time[3]%10);
	DS1302_WriteByte(DS1302_MINTUE, DS1302_Time[4]/10*16+DS1302_Time[4]%10);
	DS1302_WriteByte(DS1302_SECOND, DS1302_Time[5]/10*16+DS1302_Time[5]%10);
	DS1302_WriteByte(DS1302_DAY, DS1302_Time[6]/10*16+DS1302_Time[6]%10);
	DS1302_WriteByte(DS1302_WP,0x80);//此句WP给0x80，打开芯片写保护
}

void DS1302_ReadTime(void) //此函数读取时钟芯片的数据，写到数组DS1302_Time里
{
	unsigned char Temp;
	Temp = DS1302_ReadByte(DS1302_YEAR);//进去就被 或运算 置1，变成读，读BCD码
	DS1302_Time[0] = Temp/16*10+Temp%16;
	
	Temp = DS1302_ReadByte(DS1302_MONTH);//月
	DS1302_Time[1] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_DATE);
	DS1302_Time[2] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_HOUR);
	DS1302_Time[3] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_MINTUE);
	DS1302_Time[4] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_SECOND);
	DS1302_Time[5] = Temp/16*10+Temp%16;
	Temp = DS1302_ReadByte(DS1302_DAY);
	DS1302_Time[6] = Temp/16*10+Temp%16;
}
